#coding=utf-8
import os
import cv2
import sys
import numpy as np
from PIL import Image


def getImageandLabels(path):
    facesSamples=[]
    ids=[]
# '''
#     os.path.join() ： 将多个路径组合后返回
#     os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
# '''
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]

#级联分类器
    face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
    face_cascade.load('C:\\Users\\asus\\AppData\\Roaming\\Python\\Python37\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml')  # 一定要告诉编译器文件所在的具体位置

    for imagePath in imagePaths:
    # 打开图片
    #将图像转换为“灰色图像。
        PIL_img = Image.open(imagePath).convert('L')
    # 将图像转换为数组
        img_numpy = np.array(PIL_img, 'uint8')
    #人脸检测_Haar特征分类器
        faces = face_cascade.detectMultiScale(img_numpy)

        id = int(os.path.split(imagePath)[1].split('.')[0])
    #截取人脸的部分
        for x, y, w, h in faces:
            facesSamples.append(img_numpy[ y: y + h, x: x + w])
            ids.append(id)

    return facesSamples,ids

if __name__=="__main__":
    #图片路径
    path='C:\\Users\\asus\\Pictures\\Camera Roll\\face1'
    #获取图像数组和id标签数组
    faces,ids=getImageandLabels(path)   # 获取循环对象
    # 加载训练数据集文件
    recogizer = cv2.face.LBPHFaceRecognizer_create()
    # recogizer=cv2.face.FisherFaceRecognizer_create()
    # recogizer=cv2.face.FisherFaceRecognizer_create()
    #训练数据
    recogizer.train(faces, np.array(ids))


    list1 = ['', '杨洋', '吴才朋', '王俊凯', '王俊凯', '王俊凯', '杨洋', '杨洋', '杨洋', '杨洋', '杨洋','杨洋','杨洋','王俊凯']
    list2 = ['', 'yangyang', 'wucaipeng', 'wangjunkai', 'wangjunkai', 'wangjunkai', 'yangyang', 'yangyang', 'yangyang',
             'yangyang', 'yangyang']

    # 准备识别的图片
    img = cv2.imread('C:\\Users\\asus\\Pictures\\Camera Roll\\face\\David\\8.jpg')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    face_detector = cv2.CascadeClassifier(
        "C:\\Users\\asus\\AppData\\Roaming\\Python\\Python37\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml")
    faces = face_detector.detectMultiScale(gray)  # 人脸检测的核心

    for x, y, w, h in faces:
        # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 人脸识别
        # cv2.imshow('img', gray[y:y + h, x: x + w])
        # id, confidence = recogizer.predict(gray[y:y + h, x: x + w])

        roi = gray[x: x + w, y: y + h]
        roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)
        id, confidence = recogizer.predict(roi)
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # print('标签id:', id,'置信评分: ', confidence)
        print('他是', list1[id], '置信评分: ', confidence)
        # cv2.putText(img, list2[id], (x - 10, y + 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
    cv2.imshow(' result', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()